<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`预览 - ${document?.name}`"
    width="80%"
    @close="handleClose"
  >
    <div v-loading="loading" class="preview-container">
      <!-- PDF预览 -->
      <div v-if="document?.type === 'pdf'" class="pdf-preview">
        <iframe
          :src="previewUrl"
          width="100%"
          height="600px"
          frameborder="0"
        ></iframe>
      </div>

      <!-- 图片预览 -->
      <div v-else-if="isImage(document?.type)" class="image-preview">
        <img :src="previewUrl" alt="预览图片" style="max-width: 100%; max-height: 600px;" />
      </div>

      <!-- 文本预览 -->
      <div v-else-if="isText(document?.type)" class="text-preview">
        <pre>{{ previewContent }}</pre>
      </div>

      <!-- Office文档预览 -->
      <div v-else-if="isOffice(document?.type)" class="office-preview">
        <div class="preview-placeholder">
          <el-icon size="64"><Document /></el-icon>
          <p>{{ document?.name }}</p>
          <p>此类型文档暂不支持在线预览，请下载后查看</p>
          <el-button type="primary" @click="handleDownload">
            <el-icon><Download /></el-icon>
            下载文档
          </el-button>
        </div>
      </div>

      <!-- 其他类型 -->
      <div v-else class="unsupported-preview">
        <div class="preview-placeholder">
          <el-icon size="64"><Warning /></el-icon>
          <p>{{ document?.name }}</p>
          <p>不支持预览此类型的文档</p>
          <el-button type="primary" @click="handleDownload">
            <el-icon><Download /></el-icon>
            下载文档
          </el-button>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDownload">
          <el-icon><Download /></el-icon>
          下载
        </el-button>
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { previewDocument, downloadDocument } from '@/api/document'
import { downloadFile } from '@/utils'
import type { Document } from '@/types'

interface Props {
  visible: boolean
  document: Document | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loading = ref(false)
const previewUrl = ref('')
const previewContent = ref('')

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 获取预览内容
const fetchPreview = async () => {
  if (!props.document) return
  
  try {
    loading.value = true
    
    if (props.document.type === 'pdf' || isImage(props.document.type)) {
      // 对于PDF和图片，直接使用URL
      previewUrl.value = props.document.url
    } else if (isText(props.document.type)) {
      // 对于文本文件，获取内容
      const data = await previewDocument(props.document.id)
      previewContent.value = data.content
    }
  } catch (error) {
    ElMessage.error('预览失败')
  } finally {
    loading.value = false
  }
}

// 判断是否为图片
const isImage = (type?: string) => {
  if (!type) return false
  return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(type.toLowerCase())
}

// 判断是否为文本
const isText = (type?: string) => {
  if (!type) return false
  return ['txt', 'md', 'json', 'xml', 'csv'].includes(type.toLowerCase())
}

// 判断是否为Office文档
const isOffice = (type?: string) => {
  if (!type) return false
  return ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(type.toLowerCase())
}

// 下载文档
const handleDownload = async () => {
  if (!props.document) return
  
  try {
    const blob = await downloadDocument(props.document.id)
    downloadFile(URL.createObjectURL(blob), props.document.name)
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 关闭对话框
const handleClose = () => {
  previewUrl.value = ''
  previewContent.value = ''
  emit('update:visible', false)
}

// 监听文档变化
watch(
  () => props.document,
  (newDoc) => {
    if (newDoc && props.visible) {
      fetchPreview()
    }
  },
  { immediate: true }
)

// 监听对话框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible && props.document) {
      fetchPreview()
    }
  }
)
</script>

<style lang="scss" scoped>
.preview-container {
  min-height: 400px;
  
  .pdf-preview,
  .image-preview {
    text-align: center;
  }
  
  .text-preview {
    background: #f5f5f5;
    padding: 20px;
    border-radius: 4px;
    max-height: 600px;
    overflow-y: auto;
    
    pre {
      margin: 0;
      white-space: pre-wrap;
      word-wrap: break-word;
      font-family: 'Courier New', monospace;
      font-size: 14px;
      line-height: 1.5;
    }
  }
  
  .office-preview,
  .unsupported-preview {
    .preview-placeholder {
      text-align: center;
      padding: 60px 20px;
      color: #909399;
      
      .el-icon {
        margin-bottom: 20px;
        color: #c0c4cc;
      }
      
      p {
        margin: 10px 0;
        
        &:first-of-type {
          font-size: 16px;
          font-weight: 500;
          color: #606266;
        }
      }
      
      .el-button {
        margin-top: 20px;
      }
    }
  }
}
</style>
